<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询名称" v-model="name"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="查询路径" v-model="path"></el-input>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload
          :action="$baseUrl + '/script/import'"
          :headers="{token: user.token}"
          :on-success="handleImport"
          style="display: inline-block; margin-left: 10px"
          :show-file-list="false"
      >
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>

    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" :index="indexMethod" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="name" label="脚本名称"></el-table-column>
      <el-table-column prop="path" label="脚本路径" width="300"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="isRunning" label="状态">
        <template v-slot="scope">
          <el-tag :type="scope.row.isRunning === true ? 'success' : 'danger'">{{ scope.row.isRunning }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="340">
        <template v-slot="scope">
          <el-button size="mini" type="success" plain @click="startScript(scope.row)">启动</el-button>
          <el-button size="mini" type="warning" plain @click="stopScript(scope.row)">停止</el-button>
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
      />
    </div>

    <el-dialog title="脚本信息" :visible.sync="formVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="脚本名称"></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="如：C:\\scripts\\test.bat"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description" placeholder="用途简述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ScriptManager",
  data() {
    return {
      tableData: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      name: '',
      path: '',
      description: '',
      ids: [],
      formVisible: false,
      form: {},
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        path: [{ required: true, message: '请输入脚本路径', trigger: 'blur' }]
      },
      user: JSON.parse(localStorage.getItem('honey-user') || '{}')
    }
  },
  created() {
    this.load()
  },
  methods: {
    indexMethod(index) {
      return (this.pageNum - 1) * this.pageSize + index + 1
    },
    handleAdd() {
      this.form = {}
      this.formVisible = true
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm('确定删除该脚本吗？', '提示', { type: 'warning' }).then(() => {
        this.$request.delete('/script/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success('删除成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    delBatch() {
      if (!this.ids.length) return this.$message.warning('请选择数据')
      this.$confirm('确认批量删除这些脚本吗？', '提示', { type: 'warning' }).then(() => {
        this.$request.delete('/script/delete/batch', { data: this.ids }).then(res => {
          if (res.code === '200') {
            this.$message.success('批量删除成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    save() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const method = this.form.id ? 'put' : 'post'
          const url = this.form.id ? '/script/update' : '/script/add'
          this.$request({ url, method, data: this.form }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.formVisible = false
              this.load(1)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    startScript(row) {
      this.$request.post(`/script/start/${row.id}`).then(res => {
        console.log(res)
        if (res.code === '200') {
          this.$message.success("启动成功")
          this.load(this.pageNum)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    stopScript(row) {
      this.$request.post(`/script/stop/${row.id}`).then(res => {
        if (res.code === '200') {
          this.$message.success('脚本已停止')
          this.load(this.pageNum)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    load(pageNum) {
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/script/selectScriptData', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          description: this.description
        }
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },
    reset() {
      this.name = ''
      this.path = ''
      this.load()
    },
    exportData() {
      if (!this.ids.length) {
        window.open(this.$baseUrl + '/script/export?token=' + this.user.token + '&name=' + this.name + '&path=' + this.path)
      } else {
        window.open(this.$baseUrl + '/script/export?token=' + this.user.token + '&ids=' + this.ids.join(','))
      }
    },
    handleImport(res) {
      if (res.code === '200') {
        this.$message.success('导入成功')
        this.load(1)
      } else {
        this.$message.error(res.msg)
      }
    }
  }
}
</script>

<style scoped>
</style>
